
class BatchSelection < Pan::Component
  def initialize(collection, link_selector, text_selector)
    @items = collection
    @link_selector = link_selector
    @text_selector = text_selector
    @page_size = 8
    @current_page = 0
    session.register_object_for_backtracking(self)
  end

  def first_page?
    @current_page == 0
  end

  def last_page?
    @current_page == pages - 1
  end

  def pages
    (@items.size / @page_size.to_f).ceil
  end

  def page
    start = @current_page * @page_size
    @items[start,8]
  end

  def ltlt
    '<<'.html_safe
  end

  def gtgt
    '>>'.html_safe
  end

  def render_back_on(html)
    first_page? ? html.lit(ltlt) : html.link(ltlt) { @current_page -= 1 }
    html.nbsp
  end

  def render_forward_on(html)
    html.nbsp
    last_page? ? html.lit(gtgt) : html.link(gtgt) { @current_page += 1 }
  end

  def render_on(html)
    render_page_on(html)
    html.div(:id=>'batch','style'=>{'text-align'=>'center'}) {
      render_back_on(html)
      render_nav_on(html)
      render_forward_on(html)
    }
  end

  def render_page_on(html)
    html.ul {
      page().each do |item|
        html.li {
          render_item_on(item, html)
        }
      end
    }
  end

  def render_item_on(item, html)
    html.link(item.send(@link_selector)) {
      answer(item)
    }
    html.br
    html.lit(item.send(@text_selector))
    html.p
  end

  def render_nav_on(html)
    html.each_between('&nbsp;',(1..pages).to_a) do |page,i|
      if @current_page == i
        html.b { html.lit("#{page}") }
      else
        html.link("#{page}") {
          @current_page = i
        }
      end
    end
  end
end
